{% extends "base.html" %}
{% block title %}预约用户管理{% endblock %}

{% block content %}
<!-- 添加用户弹框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加新用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label for="addMobile" class="form-label">手机号</label>
                        <input type="text" class="form-control" id="addMobile" name="mobile">
                    </div>
                    <div class="mb-3">
                        <label for="addEmail" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="addEmail" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="appointmentMode" class="form-label">预约模式</label>
                        <select class="form-select" id="appointmentMode" name="appointmentMode">
                            <option value="NEAREST">距离最近</option>
                            <option value="INVENTORY">库存最多</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">商品列表</label>
                        <div class="list-group" id="productsCheckboxGroup">
                            <!-- 这里将通过JavaScript动态生成 -->
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveNewUserBtn">添加</button>
            </div>
        </div>
    </div>
</div>


<!-- 用户登录弹框 -->
<div class="modal fade" id="imaotaiLogin" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">预约用户登录</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="imaotaiLoginForm">
                    <input type="hidden" id="user_id" name="user_id">
                    <div class="mb-3">
                        <label for="user_name" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="user_name" name="user_name" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="mobile" class="form-label">手机号</label>
                        <input type="text" class="form-control" id="mobile" name="mobile" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="device_id" class="form-label">设备id</label>
                        <input type="text" class="form-control" id="device_id" name="device_id" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="code" class="form-label">验证码</label>
                        <input type="text" class="form-control" id="code" name="code">
                        <small class="text-muted" id="code-message"></small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="imaotaiLoginCode">1.发送验证码</button>
                <button type="button" class="btn btn-primary" id="imaotaiLoginRegister">2.登录</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑用户弹框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑用户信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" name="id">
                    <div class="mb-3">
                        <label for="editUserName" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="editUserName" name="username" readonly>
                        <small class="text-danger">用户名不可编辑，如需修改请联系管理员</small>
                    </div>
                    <div class="mb-3">
                        <label for="editMobile" class="form-label">手机号</label>
                        <input type="text" class="form-control" id="editMobile" name="mobile" readonly>
                        <small class="text-danger">手机号不可编辑，如需修改请联系管理员</small>
                    </div>
                    <div class="mb-3 row"> <!-- 使用 row 包裹 -->
                        <!-- 省份输入框 -->
                        <div class="col-md-6"> <!-- 占6列 -->
                            <label for="editProvince" class="form-label">省份</label>
                            <input type="text" class="form-control" id="editProvince" name="province">
                        </div>
                        <!-- 地区输入框 -->
                        <div class="col-md-6"> <!-- 占6列 -->
                            <label for="editCity" class="form-label">地区</label>
                            <input type="text" class="form-control" id="editCity" name="city">
                        </div>
                    </div>
                    <div class="mb-3 row"> <!-- 使用 row 包裹 -->
                        <!-- 经纬度输入框 -->
                        <div class="col-md-6"> <!-- 占6列 -->
                            <label for="editlat" class="form-label">纬度</label>
                            <input type="text" class="form-control" id="editlat" name="lat">
                        </div>
                        <div class="col-md-6"> <!-- 占6列 -->
                            <label for="editlng" class="form-label">经度</label>
                            <input type="text" class="form-control" id="editlng" name="lng">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editEmail" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="editEmail" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="editAppointmentMode" class="form-label">预约模式</label>
                        <select class="form-select" id="editAppointmentMode" name="appointmentMode">
                            <option value="NEAREST">距离最近</option>
                            <option value="INVENTORY">库存最多</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">商品列表</label>
                        <div class="list-group" id="editProductsCheckboxGroup">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveEditUserBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">预约用户列表</h5>
        <button class="btn btn-success" id="addUserBtn">
            <i class="bi bi-plus-lg"></i> 添加用户
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>手机号</th>
                        <th>邮件地址</th>
                        <th>设备id</th>
                        <th>省份</th>
                        <th>地区</th>
                        <th>状态</th>
                        <th>token有效期时间</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user in imaotai_users %}
                    <tr>
                        <td>{{ user.id }}</td>
                        <td>{{ user.imaotai_user_name }}</td>
                        <td>{{ user.mobile or '未设置' }}</td>
                        <td>{{ user.email or '未设置' }}</td>
                        <td>{{ user.device_id or '未知' }}</td>
                        <td> {{ user.province_name }} </td>
                        <td> {{ user.city_name }} </td>
                        <td>{{ '已登录' if user.status == 1 else '未登录' }}</td>
                        <td>{{ user.token_expire_time }}</td>
                        <td>{{ user.create_time }}</td>
                        <td>
                            <button class="btn btn-sm btn-info imaotaiLogin-btn" data-user-id="{{ user.id }}"
                                data-user-name="{{ user.imaotai_user_name }}" data-mobile="{{ user.mobile }}"
                                data-device-id="{{ user.device_id }}">
                                登录
                            </button>
                            <button class="btn btn-sm btn-warning edit-user-btn" data-user-id="{{ user.id }}"
                                data-user-name="{{ user.imaotai_user_name }}" data-mobile="{{ user.mobile }}"
                                data-email="{{ user.email }}" data-appointment-mode="{{ user.appointmentMode }}"
                                data-province-name="{{user.province_name}}" data-city-name="{{user.city_name}}"
                                data-lat="{{user.lat}}" data-lng="{{user.lng}}" data-products="{{ user.products}}">
                                修改
                            </button>
                            <button class="btn btn-sm btn-danger delete-user-btn"
                                data-user-id="{{ user.id }}">删除</button>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    $(document).ready(function () {
        // 添加i茅用户按钮点击弹框事件
        $('#addUserBtn').click(function () {
            $('#addUserForm')[0].reset(); // 重置表单
            $('#addStatus').val('0'); // 设置默认状态
            $('#addUserModal').modal('show');

            // 从后台获取商品列表数据
            let checkboxesHtml = '';
            $.ajax({
                url: '/api/imaotai/products',
                type: 'POST',
                success: function (response) {
                    if (response.success) {
                        response.data.forEach(element => {

                            checkboxesHtml += `
                                                <label class="list-group-item">
                                                    <input class="form-check-input me-1" type="checkbox" name="products" value="${element.product_id}">
                                                        ${element.product_name}
                                                </label>
                                            `;
                        });

                        $('#productsCheckboxGroup').html(checkboxesHtml);
                    } else {
                        $('#productsCheckboxGroup').html('<div class="text-danger">加载商品列表失败</div>');
                    }
                },
                error: function () {
                    $('#productsCheckboxGroup').html('<div class="text-danger">请求失败，请稍后重试</div>');
                }
            });
        });

        // 保存i茅用户按钮点击按钮
        $('#saveNewUserBtn').click(function () {

            // 转序列化
            const formData = $('#addUserForm').serialize()

            // 简单前端验证
            if (!$('#addMobile').val()) {
                alert('手机号不能为空');
                return;
            }

            $.ajax({
                url: '/api/imaotai/users/add',
                type: 'POST',
                data: formData,
                beforeSend: function () {
                    $('#saveNewUserBtn').prop('disabled', true).html('添加中...');
                },
                success: function (response) {
                    if (response.success) {
                        $('#addUserModal').modal('hide');
                        location.reload(); // 刷新页面
                    } else {
                        alert(response.message || '添加失败');
                    }
                },
                error: function () {
                    alert('请求失败，请稍后重试');
                },
                complete: function () {
                    $('#saveNewUserBtn').prop('disabled', false).html('添加');
                }
            });
        });

        // i茅用户登录按钮点击弹框事件
        $('.imaotaiLogin-btn').click(function () {
            // 获取用户数据
            const user_id = $(this).data('user-id');
            const user_name = $(this).data('user-name');
            const mobile = $(this).data('mobile');
            const device_id = $(this).data('device-id')

            // 填充表单数据
            $('#user_id').val(user_id);
            $('#user_name').val(user_name);
            $('#mobile').val(mobile || '');
            $('#device_id').val(device_id);
            // 提示信息置空
            $('#code-message').text('');
            // 显示弹框
            $('#imaotaiLogin').modal('show');
        });

        // 验证码发送按钮
        $('#imaotaiLoginCode').click(function () {
            const $btn = $(this);
            let countdown = 60;


            // 禁用按钮并开始倒计时
            $btn.prop('disabled', true);
            const timer = setInterval(function () {
                $btn.text(`${countdown}秒后重试`);
                countdown--;

                if (countdown < 0) {
                    clearInterval(timer);
                    $btn.text('发送验证码').prop('disabled', false);
                }
            }, 1000);

            const formData = $('#imaotaiLoginForm').serialize();
            $.ajax({
                url: '/api/imaotai/users/code',
                type: 'POST',
                data: formData,
                success: function (response) {
                    // 验证码提示
                    $('#code-message').text(response.message);
                },
                error: function () {
                    alert('请求失败，请稍后重试');
                }
            });
        });

        // 登录按钮
        $('#imaotaiLoginRegister').click(function () {
            const formData = $('#imaotaiLoginForm').serialize();

            $.ajax({
                url: '/api/imaotai/users/login',
                type: 'POST',
                data: formData,
                success: function (response) {
                    if (response.success) {
                        $('#imaotaiLoginForm').modal('hide');
                        location.reload(); // 刷新页面
                    } else {
                        alert(response.message || '保存失败');
                    }
                },
                error: function () {
                    alert('请求失败，请稍后重试');
                }
            });
        });

        // 修改用户按钮点击弹框事件
        $('.edit-user-btn').click(function () {
            const userId = $(this).data('user-id');
            const user_name = $(this).data('user-name');
            const mobile = $(this).data('mobile');
            const email = $(this).data('email');
            const appointmentMode = $(this).data('appointment-mode');
            const province_name = $(this).data('province-name');
            const city_name = $(this).data('city-name');
            const lat = $(this).data('lat');
            const lng = $(this).data('lng');
            const products = $(this).data('products');

            // 填充表单数据
            $('#editUserId').val(userId);
            $('#editUserName').val(user_name);
            $('#editMobile').val(mobile || '');
            $('#editEmail').val(email || '');
            $('#editProvince').val(province_name || '');
            $('#editCity').val(city_name || '');
            $('#editlat').val(lat || '');
            $('#editlng').val(lng || '');
            $('#editAppointmentMode').val(appointmentMode || 'NEAREST');

            // 加载商品列表并选中已选商品
            loadProducts('#editProductsCheckboxGroup', products);

            // 显示编辑弹框
            $('#editUserModal').modal('show');
        });

        // 保存编辑数据按钮
        $('#saveEditUserBtn').click(function () {
            const formData = $('#editUserForm').serialize();
            $.ajax({
                url: '/api/imaotai/users/update',
                type: 'POST',
                data: formData,
                success: function (response) {
                    if (response.success) {
                        // 关闭修改弹窗
                        $('#editUserModal').modal('hide');
                        // 刷新页面
                        location.reload();
                    }
                }
            });
        });


        // 删除用户按钮
        $('.delete-user-btn').click(function () {
            if (confirm('确定要删除这个用户吗？此操作不可撤销！')) {
                const userId = $(this).data('user-id');
                const $row = $(this).closest('tr');

                $.ajax({
                    url: '/api/imaotai/users/delete',
                    type: 'POST',
                    data: { id: userId },
                    success: function (response) {
                        if (response.success) {
                            $row.fadeOut(300, function () {
                                $(this).remove();
                            });
                        } else {
                            alert(response.message || '删除失败');
                        }
                    },
                    error: function () {
                        alert('请求失败，请稍后重试');
                    }
                });
            }

        })
    });

    // 加载商品列表函数
    function loadProducts(containerId, selectedProducts = []) {
        let checkboxesHtml = '<div class="spinner-border spinner-border-sm" role="status"><span class="visually-hidden">Loading...</span></div>';
        $(containerId).html(checkboxesHtml);

        $.ajax({
            url: '/api/imaotai/products',
            type: 'POST',
            success: function (response) {
                if (response.success) {
                    checkboxesHtml = '';
                    response.data.forEach(element => {
                        const selectedProductsStr = String(selectedProducts || ""); // 确保是字符串
                        const selectedProductsArray = selectedProductsStr.split(',').filter(Boolean);
                        const isChecked = selectedProductsArray.includes(String(element.product_id)) ? 'checked' : '';
                        checkboxesHtml += `
                                <label class="list-group-item">
                                    <input class="form-check-input me-1" type="checkbox" name="products" value="${element.product_id}" ${isChecked}>
                                    ${element.product_name}
                                </label>
                            `;
                    });
                    $(containerId).html(checkboxesHtml);
                } else {
                    $(containerId).html('<div class="text-danger">加载商品列表失败</div>');
                }
            },
            error: function () {
                $(containerId).html('<div class="text-danger">请求失败，请稍后重试</div>');
            }
        });
    }

</script>
{% endblock %}